package com.kbbywyclient.ui.activity;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.kbbywyclient.R;
import com.kbbywyclient.app.API;
import com.kbbywyclient.app.App;
import com.kbbywyclient.data.entity.Event;
import com.kbbywyclient.data.entity.MobileLoginOfRegist;
import com.kbbywyclient.data.entity.ModifyOfRegistPassWord;
import com.kbbywyclient.data.entity.RegistUser;
import com.kbbywyclient.data.entity.User;
import com.kbbywyclient.di.AppComponent;
import com.kbbywyclient.di.module.RegisterModule;
import com.kbbywyclient.presenter.RegisterPresenter;
import com.kbbywyclient.ui.activity.base.BaseActivity;
import com.kbbywyclient.ui.contarct.RegisterContract;
import com.kbbywyclient.util.ActivitySkipUtil;
import com.kbbywyclient.util.CheckFormat;
import com.kbbywyclient.util.StringUtil;
import com.kbbywyclient.util.ToastUtil;
import com.kbbywyclient.util.ViewUtils;
import com.kbbywyclient.util.pre.PreUtils;
import com.kbbywyclient.widget.CustomDialog;
import com.kbbywyclient.widget.CustomToolBar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by FHW
 * on 2017/3/23
 */

public class RegisterActivity extends BaseActivity implements RegisterContract.View {

    @Inject
    RegisterPresenter registerPresenter;

    @BindView(R.id.v_toolbar)
    CustomToolBar v_toolbar;
//    @BindView(R.id.ll_register_mb)
//    LinearLayout ll_register_mb;

    @BindView(R.id.ll_register_one)
    LinearLayout ll_register_one;
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.tv_get_Code)
    TextView tv_get_Code;
    @BindView(R.id.et_v_code)
    EditText et_v_code;
    @BindView(R.id.tv_register)
    TextView tv_register;

    @BindView(R.id.rl_register_two)
    RelativeLayout rl_register_two;
    @BindView(R.id.et_pwd)
    EditText et_pwd;
    @BindView(R.id.et_pwd_again)
    EditText et_pwd_again;
    @BindView(R.id.et_v_invite_code)
    EditText et_v_invite_code;
    @BindView(R.id.tv_register_sumbit)
    TextView tv_register_sumbit;
    @BindView(R.id.cb_agree)
    CheckBox cb_agree;
    @BindView(R.id.tv_agreement)
    TextView tv_agreement;

    private String str_phone = "";
    private String str_code = "";
    private String inviteCode="";
    private String str_pwd = "";
    private String str_pwd_again = "";

    private String SalesID = "";

    //验证码
    private final int START_CODE = 1;
    private final int COUNT_CODE = 2;
    private final int END_CODE = 3;
    private boolean isGetCode = false;
    private final int GET_CODE_TIME = 90;
    private int codeTime = 0;

    private CustomDialog dialog = null;

    private boolean isCheck = true;

    @Override
    public int provideContentViewId() {
        return R.layout.activity_register;
    }

    @OnClick({R.id.tv_get_Code, R.id.tv_register, R.id.tv_register_sumbit, R.id.tv_agreement})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_get_Code://获取验证码
                if (str_phone.isEmpty()) {
                    ToastUtil.showShort("请输入手机号码");
                } else if (!CheckFormat.isMobile(str_phone)) {
                    ToastUtil.showShort("请输入正确的手机号码");
                } else {
                    if (!isGetCode) {
//                        registerPresenter.sendOfCheckMobileCode(str_phone, "1");
                        registerPresenter.checkMobile(str_phone);
                    }
                }
                break;
            case R.id.tv_register://注册
                if (isGetCode) {
                    if (!str_code.isEmpty()) {
//                        registerPresenter.getMobileCodeLoginOfRegist(SalesID, str_phone, str_code
//                                , StringUtil.getDeviceId(this), API.APPType, "广州");
                        String inviteCode=et_v_invite_code.getText().toString();
                        if(!TextUtils.isEmpty(inviteCode)){
                            //判断邀请人手机号码格式
                            if(inviteCode.length()!=11||!CheckFormat.isMobile(inviteCode)){
                                ToastUtil.showShort("邀请人手机号码根式不正确，请重新输入");
                                return;
                            }else{
                                RegisterActivity.this.inviteCode=inviteCode;
                            }
                        }
                        registerPresenter.getMobileCodeRegister(str_phone, str_code);
                    } else {
                        ToastUtil.showShort("请输入验证码");
                    }
                } else {
                    ToastUtil.showShort("请获取验证码");
                }
                break;
            case R.id.tv_register_sumbit://提交注册
                if (vertify()) {
//                    registerPresenter.getModifyOfRegistPassWord(SalesID, str_phone, str_pwd, "1", str_code, "");
//                    registerPresenter.getRegisterSetPassWord(str_phone, str_pwd, str_code, str_pwd_again, StringUtil.getDeviceId(this)
//                            , API.APPType, PreUtils.getUser(this).getCityName());
                    registerPresenter.getRegisterSetPassWord(str_phone, inviteCode,str_pwd, str_code, str_pwd_again, App.mDeviceToken
                            , API.APPType, PreUtils.getUser(this).getCityName());
                }
                break;
            case R.id.tv_agreement://协议
                ActivitySkipUtil.skipAnotherActivity(this, AgreementActivity.class);
                break;
        }
    }

    /**
     * 验证密码
     *
     * @return
     */
    private boolean vertify() {
        if (str_pwd.isEmpty()) {
            ToastUtil.showShort("请输入密码");
            return false;
        }
        if (!CheckFormat.isPwd(str_pwd)) {
            ToastUtil.showShort("密码须为6-15位");
            return false;
        }
        if (str_pwd_again.isEmpty()) {
            ToastUtil.showShort("请再次输入密码");
            return false;
        }
        if (!str_pwd.equals(str_pwd_again)) {
            ToastUtil.showShort("密码和确认密码设置未统一");
            return false;
        }
        if (!isCheck) {
            ToastUtil.showShort("请阅读并同意用户协议");
            return false;
        }

        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        setScreenName("注册页");
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        ImmersionBar.with(this).keyboardEnable(true).init();

        v_toolbar.setLeftViewOnClickLinster(v -> finish());

        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                str_phone = s.toString();
                if (CheckFormat.isMobile(str_phone)) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(et_phone.getWindowToken(), 0); //强制隐藏键盘
                    }
                }
            }
        });
        et_v_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                str_code = s.toString();
                if (CheckFormat.isCode(str_code)) {
                    if (isGetCode) {
                        tv_register.setBackgroundResource(R.drawable.textview_bg_14c095);
                    }
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(et_v_code.getWindowToken(), 0); //强制隐藏键盘
                    }
                } else {
                    tv_register.setBackgroundResource(R.drawable.textview_bg_20ffffff);
                }
            }
        });

        et_pwd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                str_pwd = s.toString();
                isSubmitRegistFillIn();
            }
        });
        et_pwd_again.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                str_pwd_again = s.toString();
                isSubmitRegistFillIn();
            }
        });

        cb_agree.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isCheck = isChecked;
            }
        });

    }

//    /**
//     * 判断手机和验证码填写完成的操作
//     */
//    private void isRegistFillIn() {
//        if (CheckFormat.isMobile(str_phone) && CheckFormat.isCode(str_code)) {
//            tv_register.setBackgroundResource(R.drawable.textview_bg_14c095);
//            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
//            if (imm.isActive()) {
//                imm.hideSoftInputFromWindow(et_phone.getWindowToken(), 0); //强制隐藏键盘
//            }
//        } else {
//            tv_register.setBackgroundResource(R.drawable.textview_bg_20ffffff);
//        }
//    }

    /**
     * 判断密码填写完成的操作
     */
    private void isSubmitRegistFillIn() {
        if (CheckFormat.isPwd(str_pwd) && CheckFormat.isPwd(str_pwd_again)) {
            tv_register_sumbit.setBackgroundResource(R.drawable.textview_bg_14c095);
            if (CheckFormat.isPwdFinish(str_pwd) && CheckFormat.isPwdFinish(str_pwd_again)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(et_pwd.getWindowToken(), 0); //强制隐藏键盘
                }
            }
        } else {
            tv_register_sumbit.setBackgroundResource(R.drawable.textview_bg_20ffffff);
        }
    }


    @Override
    public void initData() {

    }

    @Override
    public void initAppComponent(AppComponent appComponent) {
        appComponent.getRegisterComponent(new RegisterModule(this)).inject(this);
    }

    /**
     * 手机注册 回调
     *
     * @param mobileRegist
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventMainThread(Event.MobileRegist mobileRegist) {
        str_phone = mobileRegist.getStr_mobile();
        et_phone.setText(str_phone);
        if (!isGetCode) {
//            registerPresenter.sendOfCheckMobileCode(str_phone, "");
            registerPresenter.sendMobileCodeNews(str_phone);
        }
        EventBus.getDefault().removeAllStickyEvents();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showLoadingDialog(String s) {
        showProgress(s);
    }

    @Override
    public void closeLoadingDialog() {
        dismissProgress();
    }

    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case START_CODE:
                    codeTime = GET_CODE_TIME;
                    isGetCode = true;
                    handler.sendEmptyMessage(COUNT_CODE);
                    break;
                case COUNT_CODE:
                    if (codeTime <= 0) {
                        handler.sendEmptyMessage(END_CODE);
                    } else {
                        tv_get_Code.setTextColor(getResources().getColor(R.color.color_14C095));
                        ViewUtils.setText(tv_get_Code, codeTime-- + "s");
                        handler.sendEmptyMessageDelayed(COUNT_CODE, 1000);
                    }
                    break;
                case END_CODE:
                    isGetCode = false;
                    tv_get_Code.setTextColor(getResources().getColor(R.color.color_ffffff));
                    ViewUtils.setText(tv_get_Code, R.string.text_get_code);
                    break;
            }
            return false;
        }
    });

    @Override
    public void loadSucCheck(RegistUser registUser) {
        switch (registUser.getNewUser()) {
            case 0://已注册
                dialog = new CustomDialog(this, R.style.Customdialog, "该手机号已注册", "验证手机号可直接登录！", new CustomDialog.ButtonListener() {
                    @Override
                    public void left() {
                        dialog.dismiss();
                        EventBus.getDefault().post(new Event.MobileLogin(str_phone));
                        finish();
                    }

                    @Override
                    public void right() {
                        dialog.dismiss();
                    }
                }, getString(R.string.text_get_code), getString(R.string.cancel));
                dialog.show();
                break;
            case 1://未注册
//                registerPresenter.sendOfCheckMobileCode(str_phone, "");
                registerPresenter.sendMobileCodeNews(str_phone);
                break;
        }
    }

    @Override
    public void loadFaiCheck(String errorMsg) {

    }

    @Override
    public void loadSucCode(RegistUser registUser) {
        SalesID = registUser.getSalesID() + "";
        handler.sendEmptyMessage(START_CODE);
    }

    @Override
    public void loadFaiCode(String errorMsg) {

    }

    @Override
    public void loadSucLoginOfRegist(ModifyOfRegistPassWord modifyOfRegistPassWord) {
        ll_register_one.setVisibility(View.GONE);
        rl_register_two.setVisibility(View.VISIBLE);
//        ll_register_mb.setBackgroundResource(R.mipmap.img_register_mb_two);
//        this.mobileLoginOfRegist = mobileLoginOfRegist;
    }

    @Override
    public void loadFaiLoginOfRegist(String errorMsg) {

    }

    @Override
    public void loadSucModifyOfRegist(MobileLoginOfRegist mobileLoginOfRegist) {
        int city = -1;
        if (mobileLoginOfRegist.getCity() instanceof Integer) {
            city = (int) mobileLoginOfRegist.getCity();
        }
        User user = new User(
                mobileLoginOfRegist.getSalesID(),
                city,
                mobileLoginOfRegist.getCityName(),
                mobileLoginOfRegist.getGoToType(),
                mobileLoginOfRegist.getIsOpenRpacket(),
                mobileLoginOfRegist.getRole());
        // 保存用户信息
        saveUserInfo(user);
        PreUtils.setUserAccount(this, str_phone);
        if(!PreUtils.isFirstRegister(this)){
            ActivitySkipUtil.skipAnotherActivity(this, MainActivity.class);
        }else{
            HashMap<String,Object> params=new HashMap<>();
            params.put(MainActivity.SET_INDEX_FRAGMENT_B,true);
            PreUtils.setFirstRegister(this);
            ActivitySkipUtil.skipAnotherActivity(this,MainActivity.class,params);
        }
    }

    private void saveUserInfo(User user) {
        PreUtils.saveUser(this, user);
        PreUtils.setLogin(this, true);
    }

    @Override
    public void loadFaiModifyOfRegist(String errorMsg) {

    }
}
